<script setup lang="ts">
import { ref, computed, reactive, nextTick, onMounted } from 'vue'
import type { Ref, Component } from 'vue'
import { ElMessage, ElScrollbar } from 'element-plus'
import axios from 'axios'
interface message {
    type: string,
    nickName: string,
    time: string,
    message: string,
}
const messageList: Ref<message[]> = ref([])
const ws: Ref<WebSocket | null> = ref(null)

const nickName: Ref<string> = ref('')
interface loginFrom {
    name: string,
    password: string,
}
const loginFrom: loginFrom = reactive({
    name: '',
    password: '',
})

const loginChatRoom = async () => {
    const result = await axios.post('http://localhost:8080/api/login', loginFrom)
    console.log(result.data);
    if(result.data.code === 405){
        return ElMessage.error(result.data.message)
    }
    window.localStorage.setItem('token', result.data.data.token)
    window.localStorage.setItem('name', result.data.data.userInfo.name)
    window.localStorage.setItem('id', result.data.data.userInfo.id)
    nickName.value = result.data.data.userInfo.name
    document.cookie = `token=${result.data.data.token}`
    ws.value = connect(window.localStorage.getItem('name') as string)
}
onMounted(() => {
    if (window.localStorage.getItem('token')) {
        nickName.value = window.localStorage.getItem('name') as string
        ws.value = connect(window.localStorage.getItem('name') as string)
        nickName.value = window.localStorage.getItem('name') as string
    }
})
const message: Ref<string> = ref('')
const sendMessage = () => {
    // console.log('sendMessage')
    if (ws.value) {
        ws.value.send(message.value)
        message.value = ''
    }
}

const innerRef = ref<HTMLDivElement>()
const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>()

function connect(nickName: string): WebSocket {
    const hostname = window.location.hostname
    const wss = new WebSocket(`ws://${hostname}:8080/chat?nickName=${nickName}`);
    wss.onopen = () => {
        console.log('ws.onopen')
    }
    wss.onmessage = (event) => {
        const data = JSON.parse(event.data)
        if(data.type === 'message'){
            messageList.value.push(data)
            nextTick(() => {
                scrollbarRef.value!.setScrollTop(innerRef.value!.clientHeight)
            })
        }else if(data.type === 'error'){
            document.cookie = ''
            window.localStorage.clear()
            ElMessage.error(data.message)
        }
    }
    wss.onclose = () => {
        ws.value = null
    }
    return wss
}
</script>

<template>
    <!-- 登陆窗口 -->
    <section class="login-window" v-if="!ws">
        <el-form v-model="loginFrom" label-width="60px">
            <el-form-item label="用户名">
                <el-input v-model.trim="loginFrom.name" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="密码">
                <el-input v-model.trim="loginFrom.password" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="text" @click="loginChatRoom">进入聊天室</el-button>
            </el-form-item>
        </el-form>
    </section>
    <!-- 聊天室界面 -->
    <section v-else class="chat-container">
        <div class="message-container">
            <el-scrollbar ref="scrollbarRef">
                <div ref="innerRef">
                    <div v-for="m in messageList" class="message-box"
                        :class="{ 'message-box-direction-reverse': m.nickName === nickName }">
                        <div>{{ m.nickName.slice(0, 1) }}</div>
                        <!-- <div>时间：{{ m.time }}</div> -->
                        <div>{{ m.message }}</div>
                        <div :class="{
                            'triangle': true,
                            'triangle-right': m.nickName === nickName,
                            'triangle-left': m.nickName !== nickName,
                        }" />
                    </div>
                </div>
            </el-scrollbar>
        </div>
        <div class="input-container">
            <el-input type="textarea" :rows="6" v-model="message" placeholder="请输入要发送的消息"></el-input>
            <el-button type="primary" @click="sendMessage">发送</el-button>
        </div>
    </section>
</template>

<style scoped>
.login-window {
    width: 400px;
    height: 300px;
    border: 1px solid #ccc;
    background: #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -280px;
    margin-left: -200px;
    border-radius: 10px;
    box-sizing: border-box;
    padding: 10px;
    box-shadow: 5px 5px 5px rgba(51, 51, 51, 0.534);
}

.chat-container {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background: linear-gradient(135deg, #184e68, #57ca85);
    box-sizing: border-box;
    padding: 10px;
}

.message-container {
    height: calc(100% - 190px);
    /* background: #ffffff5c; */
    background: #fff;
    border-radius: 10px;
    box-sizing: border-box;
    padding: 10px;
    margin-bottom: 10px;
    box-shadow: 5px 5px 5px rgba(51, 51, 51, 0.534);
}

.message-box {
    margin-bottom: 10px;
    font-size: 14px;
    display: flex;
    position: relative;

}

.message-box-direction-reverse {
    flex-direction: row-reverse;
}

.message-box :nth-child(1) {
    height: 40px;
    width: 40px;
    border-radius: 20px;
    border: 1px solid #333;
    text-align: center;
    line-height: 40px;
    font-size: 20px;

}

.message-box :nth-child(2) {
    border: 1px solid #333;
    padding: 5px;
    border-radius: 5px;
    max-width: 200px;
    word-break: break-all;
    background-color: #57ca85;
    display: flex;
    align-items: center;
    margin-left: 10px;
    margin-right: 10px;
}

.message-box .triangle {
    position: absolute;
    top: 20px;
    margin-top: -4px;
    height: 8px;
    width: 8px;
    background-color: #57ca85;
}

.message-box .triangle-left {
    left: 48px;
    border-left: 1px solid #333;
    border-top: 1px solid #333;
    transform: rotate(-45deg);
}

.message-box .triangle-right {
    right: 48px !important;
    border-right: 1px solid #333;
    border-top: 1px solid #333;
    transform: rotate(45deg);
}

.input-container {
    /* background: #ffffff5c; */
    background: #fff;
    border-radius: 10px;
    box-sizing: border-box;
    height: 180px;
    padding: 10px;
    box-shadow: 5px 5px 5px rgba(51, 51, 51, 0.534);
    display: flex;
    flex-direction: column;
    justify-content: center;
    /* align-items: center; */
}
</style>
